// import { clipboard } from '@ve/utils/clipboard'
// import { jsonToTable } from '@ve/utils/jsonToTable'

import isEmpty from 'lodash/isEmpty'
// import { Toast } from 'vant'
import { ElMessage } from 'element-plus'
import { Toast } from 'vant'
import { translateTitle } from '@/utils/i18n'

//必须带done回调 执行完成调用
export default function pdaGetCardData({ vm, action, done, eventName }) {
  let { cardSelect, getDataKey, emptyMsg } = action.extension
  let cardSelf = null

  if (!isEmpty(cardSelect.value)) {
    // 选中了卡片
    cardSelf = vm.vuiComponents[cardSelect.value[0]]?.self

    const choiceArr = cardSelf.cardData.filter((v) => {
      return v.check
    })
    // 若是有选中的数据
    if (!isEmpty(choiceArr)) {
      let _dataArr = []
      // 表格选中数据字段
      if (!isEmpty(getDataKey.value)) {
        const getDataKeyList = getDataKey.value.split(',')
        // 多选有固定的key 返回固定key对应的值
        const result = choiceArr.reduce((acc, cur) => {
          // 累加数据
          getDataKeyList.forEach((v) => {
            acc[v] += cur[v] + ','
          })
          return acc
        }, Object.fromEntries(getDataKeyList.map((key) => [key, ''])))
        // 删除最后一个逗号
        getDataKeyList.forEach((v) => {
          result[v] = result[v].slice(0, -1)
        })
        _dataArr = result
      } else {
        // 多选没有固定key 返回所有key对应的字符串
        const result = {}
        choiceArr.forEach((obj) => {
          for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              if (Object.prototype.hasOwnProperty.call(result, key)) {
                result[key] += obj[key] + ','
              } else {
                result[key] = obj[key] + ','
              }
            }
          }
        })

        Object.keys(choiceArr[0]).forEach((v) => {
          result[v] = result[v].slice(0, -1)
        })
        _dataArr = result
      }
      console.log('往下传值', _dataArr)
      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: _dataArr,
      })
      done(null, _dataArr)
    } else {
      console.log('emptyMsg', emptyMsg.value)
      if (emptyMsg && !isEmpty(emptyMsg.value)) {
        Toast(translateTitle(emptyMsg.value))
      } else {
        Toast(translateTitle('Pda.elements.请选择卡片数据'))
      }
      vm[`${eventName}IsRunning`] = false
    }
  } else {
    ElMessage({
      showClose: true,
      message: translateTitle('Pda.elements.请选择卡片!'),
      type: 'error',
    })
    console.log('eventName', eventName)
    // 修改任务队列执行状态，防止下一次事件被拦截
    vm[`${eventName}IsRunning`] = false
  }
}
